package game.module.turntables.processor;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.RandomUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import db.proto.PlayTurntable.ATurntables;
import db.proto.PlayTurntable.PTurntable;
import game.common.PlayingRoleMsgProcessor;
import game.entity.PlayingRole;
import game.module.item.logic.ItemManager;
import game.module.template.TurntableTemplate;
import game.module.turntables.bean.TurntableBean;
import game.module.turntables.dao.TurntableCache;
import game.module.turntables.dao.TurntablesTemplateCache;
import game.module.turntables.logic.TurntableDBHelper;
import game.module.user.bean.Activity_stateBean;
import game.module.user.dao.ActivitystateCache;
import lion.common.MsgCodeAnn;
import lion.math.RandomDispatcher;
import lion.netty4.message.MyRequestMessage;
import lion.netty4.message.RequestMessageRaw;
import lion.netty4.message.RequestProtoMessage;
import lua.LuaMessageHall.C2SLoginTurntable;
import lua.LuaMessageHall.S2CLoginTurntable;
import lua.LuaMessageLogin.S2ErrorCode;

@MsgCodeAnn(msgcode = C2SLoginTurntable.id, accessLimit = 500)
public class Login_turntableProcessor extends PlayingRoleMsgProcessor {

	private static Logger logger = LoggerFactory.getLogger(Login_turntableProcessor.class);

	@Override
	public void process(PlayingRole playingRole, RequestMessageRaw requestMessage) throws Exception {


		int playerId = playingRole.getId();

		Activity_stateBean activitybean = ActivitystateCache.getInstance().getActivitystate(playerId);
		if (activitybean == null) {
			S2ErrorCode respMsg = new S2ErrorCode(114);
			playingRole.writeAndFlush(respMsg.build(playingRole.alloc()));
			return;// 今天已经使用过等登陆
		}
		if (!activitybean.isTurntable_state()) {
			S2ErrorCode respMsg = new S2ErrorCode(114);
			playingRole.writeAndFlush(respMsg.build(playingRole.alloc()));
			return;// 今天已经使用过等登陆
		}
		TurntableBean turntable = TurntableCache.getInstance().getTurntable(playerId);
		Map<Integer, PTurntable> TypeOne = new HashMap<Integer, PTurntable>();
		if (turntable != null) {

			ATurntables aturntable = turntable.getTurntableList();
			for (PTurntable abean : aturntable.getTurnTableList()) {
				if (abean.getType() == 1) {
					TypeOne.put(abean.getTurntableId(), abean);
				}
			}
		}
		// Map<Integer, PTurntable> TypeOne = turntable.get(1);

		List<TurntableTemplate> TurntableTemplatelist = TurntablesTemplateCache.getInstance().getlogin_turntable();
		if (TypeOne == null || TypeOne.size() <= 0) {
			List<TurntableTemplate> allTemplatelist = TurntablesTemplateCache.getInstance().getturntable();
			TurntableBean aBean = new TurntableBean();
			ATurntables.Builder playturntable = ATurntables.newBuilder();
			for (TurntableTemplate aTurntable : allTemplatelist) {
				if (aTurntable.getNonetime() > 0 || aTurntable.getMinhowtime() > 0 || aTurntable.getMaxhowtime() > 0
						|| aTurntable.getMaxtime() > 0) {
					PTurntable atruetable = PTurntable.newBuilder().setTurntableId(aTurntable.getId())
							.setGainRetainNum(aTurntable.getNonetime()).setType(aTurntable.getType())
							.setSureGainRemainNum(
									RandomUtils.nextInt(aTurntable.getMinhowtime(), aTurntable.getMaxhowtime()))
							.build();
					TypeOne.put(atruetable.getTurntableId(), atruetable);
					playturntable.addTurnTable(atruetable);
				}

			}
			ATurntables playertable = playturntable.build();
			aBean.setPlayerid(playerId);
			aBean.setTurntableList(playertable);
			turntable = aBean;
			TurntableCache.getInstance().turntableCacheAll.put(playerId, aBean);
			TurntableDBHelper.getInstance().asyncAddTurntable(aBean);
		}

		// 获得保底奖励
		int item_id = 0;
		for (TurntableTemplate aTurntable : TurntableTemplatelist) {
			if (TypeOne.containsKey(aTurntable.getId())) {// 如果缓存中
				PTurntable thisBean = TypeOne.get(aTurntable.getId());
				if (aTurntable.getMinhowtime() > 0) {// 模板中存在一定会获得次数

					if (thisBean.getSureGainRemainNum() <= 1) { // 到达次数本次必获得
						PTurntable newbean = thisBean.toBuilder()
								.setSureGainRemainNum(
										RandomUtils.nextInt(aTurntable.getMinhowtime(), aTurntable.getMaxhowtime()))
								.build();
						TypeOne.put(newbean.getTurntableId(), newbean);
						
						ItemManager.getInstance().addItem(playingRole, aTurntable.getItemid(), aTurntable.getNum(),
								playingRole.getId());

						ATurntables turntables = turntable.getTurntableList();
						ATurntables playertable = getnewturn(turntables, TypeOne);
						turntable.setTurntableList(playertable);

						logger.info("本次为必得登陆转盘 playid={},本次转盘id={},", playingRole.getId(), aTurntable.getId());
						S2CLoginTurntable msg = new S2CLoginTurntable();
						msg.item_id = (byte) aTurntable.getItemid();
						playingRole.writeAndFlush(msg.build(playingRole.alloc()));
						TurntableDBHelper.getInstance().asyncUpdateTurntable(turntable);
						return;// 一定返回本次奖励
					}
					PTurntable newbean = thisBean.toBuilder().setSureGainRemainNum(thisBean.getSureGainRemainNum() - 1)
							.build();
					TypeOne.put(newbean.getTurntableId(), newbean);

					logger.info("num={}", thisBean);
					// TurntableDBHelper.getInstance().asyncUpdateTurntable(thisBean);
				}
			}
			if ((aTurntable.getNonetime() > 0 || aTurntable.getMinhowtime() > 0 || aTurntable.getMaxhowtime() > 0
					|| aTurntable.getMaxtime() > 0) && !TypeOne.containsKey(aTurntable.getId())) {
				// 添加单个
				PTurntable atruetable = PTurntable.newBuilder().setTurntableId(aTurntable.getId())
						.setGainRetainNum(aTurntable.getNonetime()).setType(aTurntable.getType()).setSureGainRemainNum(
								RandomUtils.nextInt(aTurntable.getMinhowtime(), aTurntable.getMaxhowtime()))
						.build();
				ATurntables turntables = turntable.getTurntableList();
				ATurntables playertable = addnewturn(turntables, atruetable);
				turntable.setTurntableList(playertable);
				TurntableDBHelper.getInstance().asyncUpdateTurntable(turntable);
				
			}
		}

		RandomDispatcher<Integer> rand = new RandomDispatcher<>();
		for (TurntableTemplate aTurntable : TurntableTemplatelist) {
			if (TypeOne.containsKey(aTurntable.getId())) {// 如果缓存中
				PTurntable thisBean = TypeOne.get(aTurntable.getId());
				if (aTurntable.getNonetime() > 0 && thisBean.getGainRetainNum() > 0) {
					PTurntable newbean = thisBean.toBuilder().setGainRetainNum(thisBean.getGainRetainNum() - 1).build();// 距离可以加入随机数组近一步
					TypeOne.put(newbean.getTurntableId(), newbean);
					continue;
				}

			}
			rand.put(aTurntable.getProbability(), TurntableTemplatelist.indexOf(aTurntable));
		}
		int index = rand.random();
		TurntableTemplate aTurntable = TurntableTemplatelist.get(index);
		if (aTurntable.getNonetime() > 0) {
			PTurntable thisBean = TypeOne.get(aTurntable.getId());
			thisBean.toBuilder().setGainRetainNum(aTurntable.getNonetime());

		}
		ItemManager.getInstance().addItem(playingRole, aTurntable.getItemid(), aTurntable.getNum(),
				playingRole.getId());
		S2CLoginTurntable msg = new S2CLoginTurntable();
		msg.item_id = (byte) aTurntable.getItemid();
		
		playingRole.writeAndFlush(msg.build(playingRole.alloc()));
		logger.info("登陆转盘 playid={},本次转盘id={},", playingRole.getId(), aTurntable.getId());
		ATurntables turntables = turntable.getTurntableList();
		ATurntables playertable = getnewturn(turntables, TypeOne);
		turntable.setTurntableList(playertable);
		TurntableDBHelper.getInstance().asyncUpdateTurntable(turntable);
	}

	public static void test(PlayingRole playingRole) {

		int playerId = playingRole.getId();

		Activity_stateBean activitybean = ActivitystateCache.getInstance().getActivitystate(playerId);
		if (activitybean == null) {
			S2ErrorCode respMsg = new S2ErrorCode(114);
			playingRole.writeAndFlush(respMsg.build(playingRole.alloc()));
			return;// 今天已经使用过等登陆
		}
		if (!activitybean.isTurntable_state()) {
			S2ErrorCode respMsg = new S2ErrorCode(114);
			playingRole.writeAndFlush(respMsg.build(playingRole.alloc()));
			return;// 今天已经使用过等登陆
		}
		TurntableBean turntable = TurntableCache.getInstance().getTurntable(playerId);
		Map<Integer, PTurntable> TypeOne = new HashMap<Integer, PTurntable>();
		if (turntable != null) {

			ATurntables aturntable = turntable.getTurntableList();
			for (PTurntable abean : aturntable.getTurnTableList()) {
				if (abean.getType() == 1) {
					TypeOne.put(abean.getTurntableId(), abean);
				}
			}
		}
		// Map<Integer, PTurntable> TypeOne = turntable.get(1);

		List<TurntableTemplate> TurntableTemplatelist = TurntablesTemplateCache.getInstance().getlogin_turntable();
		if (TypeOne == null || TypeOne.size() <= 0) {
			List<TurntableTemplate> allTemplatelist = TurntablesTemplateCache.getInstance().getturntable();
			TurntableBean aBean = new TurntableBean();
			ATurntables.Builder playturntable = ATurntables.newBuilder();
			for (TurntableTemplate aTurntable : allTemplatelist) {
				if (aTurntable.getNonetime() > 0 || aTurntable.getMinhowtime() > 0 || aTurntable.getMaxhowtime() > 0
						|| aTurntable.getMaxtime() > 0) {
					PTurntable atruetable = PTurntable.newBuilder().setTurntableId(aTurntable.getId())
							.setGainRetainNum(aTurntable.getNonetime()).setType(aTurntable.getType())
							.setSureGainRemainNum(
									RandomUtils.nextInt(aTurntable.getMinhowtime(), aTurntable.getMaxhowtime()))
							.build();
					TypeOne.put(atruetable.getTurntableId(), atruetable);
					playturntable.addTurnTable(atruetable);
				}

			}
			ATurntables playertable = playturntable.build();
			aBean.setPlayerid(playerId);
			aBean.setTurntableList(playertable);
			turntable = aBean;
			TurntableCache.getInstance().turntableCacheAll.put(playerId, aBean);
			TurntableDBHelper.getInstance().asyncAddTurntable(aBean);
		}

		// 获得保底奖励
		int item_id = 0;
		for (TurntableTemplate aTurntable : TurntableTemplatelist) {
			if (TypeOne.containsKey(aTurntable.getId())) {// 如果缓存中
				PTurntable thisBean = TypeOne.get(aTurntable.getId());
				if (aTurntable.getMinhowtime() > 0) {// 模板中存在一定会获得次数

					if (thisBean.getSureGainRemainNum() <= 1) { // 到达次数本次必获得
						PTurntable newbean = thisBean.toBuilder()
								.setSureGainRemainNum(
										RandomUtils.nextInt(aTurntable.getMinhowtime(), aTurntable.getMaxhowtime()))
								.build();
						TypeOne.put(newbean.getTurntableId(), newbean);
						
						ItemManager.getInstance().addItem(playingRole, aTurntable.getItemid(), aTurntable.getNum(),
								playingRole.getId());

						ATurntables turntables = turntable.getTurntableList();
						ATurntables playertable = getnewturn(turntables, TypeOne);
						turntable.setTurntableList(playertable);

						logger.info("本次为必得登陆转盘 playid={},本次转盘id={},", playingRole.getId(), aTurntable.getId());
						S2CLoginTurntable msg = new S2CLoginTurntable();
						msg.item_id = (byte) aTurntable.getItemid();
					
						playingRole.writeAndFlush(msg.build(playingRole.alloc()));
						TurntableDBHelper.getInstance().asyncUpdateTurntable(turntable);
						return;// 一定返回本次奖励
					}
					PTurntable newbean = thisBean.toBuilder().setSureGainRemainNum(thisBean.getSureGainRemainNum() - 1)
							.build();
					TypeOne.put(newbean.getTurntableId(), newbean);

					logger.info("num={}", thisBean);
					// TurntableDBHelper.getInstance().asyncUpdateTurntable(thisBean);
				}
			}
			if ((aTurntable.getNonetime() > 0 || aTurntable.getMinhowtime() > 0 || aTurntable.getMaxhowtime() > 0
					|| aTurntable.getMaxtime() > 0) && !TypeOne.containsKey(aTurntable.getId())) {
				// 添加单个
				PTurntable atruetable = PTurntable.newBuilder().setTurntableId(aTurntable.getId())
						.setGainRetainNum(aTurntable.getNonetime()).setType(aTurntable.getType()).setSureGainRemainNum(
								RandomUtils.nextInt(aTurntable.getMinhowtime(), aTurntable.getMaxhowtime()))
						.build();
				ATurntables turntables = turntable.getTurntableList();
				ATurntables playertable = addnewturn(turntables, atruetable);
				turntable.setTurntableList(playertable);
				TurntableDBHelper.getInstance().asyncUpdateTurntable(turntable);
				
			}
		}

		RandomDispatcher<Integer> rand = new RandomDispatcher<>();
		for (TurntableTemplate aTurntable : TurntableTemplatelist) {
			if (TypeOne.containsKey(aTurntable.getId())) {// 如果缓存中
				PTurntable thisBean = TypeOne.get(aTurntable.getId());
				if (aTurntable.getNonetime() > 0 && thisBean.getGainRetainNum() > 0) {
					PTurntable newbean = thisBean.toBuilder().setGainRetainNum(thisBean.getGainRetainNum() - 1).build();// 距离可以加入随机数组近一步
					TypeOne.put(newbean.getTurntableId(), newbean);
					continue;
				}

			}
			rand.put(aTurntable.getProbability(), TurntableTemplatelist.indexOf(aTurntable));
		}
		int index = rand.random();
		TurntableTemplate aTurntable = TurntableTemplatelist.get(index);
		if (aTurntable.getNonetime() > 0) {
			PTurntable thisBean = TypeOne.get(aTurntable.getId());
			thisBean.toBuilder().setGainRetainNum(aTurntable.getNonetime());

		}
		ItemManager.getInstance().addItem(playingRole, aTurntable.getItemid(), aTurntable.getNum(),
				playingRole.getId());
		S2CLoginTurntable msg = new S2CLoginTurntable();
		msg.item_id = (byte) aTurntable.getItemid();
		
		playingRole.writeAndFlush(msg.build(playingRole.alloc()));
		logger.info("登陆转盘 playid={},本次转盘id={},", playingRole.getId(), aTurntable.getId());

		ATurntables turntables = turntable.getTurntableList();

		ATurntables playertable = getnewturn(turntables, TypeOne);
		turntable.setTurntableList(playertable);
		TurntableDBHelper.getInstance().asyncUpdateTurntable(turntable);
	}
	
	public static ATurntables addnewturn(ATurntables oldturntable, PTurntable atruetables) {
		ATurntables.Builder playturntables = ATurntables.newBuilder();
		for (int j = 0; j < oldturntable.getTurnTableCount(); j++) {
			// newturntables.
			PTurntable atruetable = null;
			atruetable = PTurntable.newBuilder().setTurntableId(oldturntable.getTurnTable(j).getTurntableId())
						.setGainRetainNum(oldturntable.getTurnTable(j).getGainRetainNum()).setType(oldturntable.getTurnTable(j).getType())
						.setSureGainRemainNum(oldturntable.getTurnTable(j).getSureGainRemainNum()).build();

			playturntables.addTurnTable(atruetable);
		}
		playturntables.addTurnTable(atruetables);
		ATurntables playertable = playturntables.build();
		return playertable;

	}
	public static ATurntables getnewturn(ATurntables oldturntable, Map<Integer, PTurntable> TypeOne) {
		ATurntables.Builder playturntables = ATurntables.newBuilder();
		for (int j = 0; j < oldturntable.getTurnTableCount(); j++) {
			// newturntables.
			PTurntable atruetable = null;
			if (TypeOne.containsKey(oldturntable.getTurnTable(j).getTurntableId())) {//类型一
				PTurntable thisBean = TypeOne.get(oldturntable.getTurnTable(j).getTurntableId());
				atruetable = PTurntable.newBuilder().setTurntableId(thisBean.getTurntableId())
						.setGainRetainNum(thisBean.getGainRetainNum()).setType(1)
						.setSureGainRemainNum(thisBean.getSureGainRemainNum()).build();
			} else {//类型二
				atruetable = PTurntable.newBuilder().setTurntableId(oldturntable.getTurnTable(j).getTurntableId())
						.setGainRetainNum(oldturntable.getTurnTable(j).getGainRetainNum()).setType(2)
						.setSureGainRemainNum(oldturntable.getTurnTable(j).getSureGainRemainNum()).build();

			}
			playturntables.addTurnTable(atruetable);
		}
		ATurntables playertable = playturntables.build();
		return playertable;

	}

	@Override
	public void processProto(PlayingRole playingRole, RequestProtoMessage request) throws Exception {

	}

	@Override
	public void processWebsocket(PlayingRole playingRole, MyRequestMessage request) throws Exception {

	}

	public static void main(String[] args) {

	}

}
